<?php
class Application {
	/**
	 * module
	 *
	 * @var string
	 */
	private $module;
	/**
	 * Action请求
	 *
	 * @var string
	 */
	private $action;
	
	/**
	 * URI转发器
	 *
	 * @var object
	 */
	public $route;
	
	/**
	 * 构造函数.
	 * 
	 * @return void
	 * @access public
	 * 
	 */
	public function __construct() {
		if (DEBUG === TRUE) {
			echo '--- Application construct!' . '<br/>';
		}
	}
	
	/**
	 * Run the application
	 *    
	 * @return void
	 * @access public
	 *
	 */
	public function run($start = TRUE) {
		$this->route ();
		if ($start === TRUE) {
			$this->setHeader ();
			if (DEBUG === TRUE) { echo "<h3>模块：{$_GET ['module']} 动作：{$_GET ['action']}</h3>";}
		}
		$this->filterRequest ();
	}
	
	public function route() {
		Mid::loadClass ( 'route' );
		new Route ( $this->route );
		$route = $this->route;
		if (isset ( $route ['/'] )) {
			$defaultModule = $defaultAction = NULL;
			@list ( $defaultModule, $defaultAction ) = explode ( '/', $route ['/'] );
		}
		$defaultModule = isset ( $defaultModule ) ? $defaultModule : DEFAULT_MODULE;
		$defaultAction = isset ( $defaultAction ) ? $defaultAction : DEFAULT_ACTION;
		$_GET ['module'] = $this->module = isset ( $_GET ['module'] ) && $_GET ['module'] != '' ? $_GET ['module'] : $defaultModule;
		$_GET ['action'] = $this->action = isset ( $_GET ['action'] ) && $_GET ['action'] != '' ? $_GET ['action'] : $defaultAction;
		return $this;
	}
	
	/**
	 * set public header
	 * 
	 * @return void
	 * @access private
	 *
	 */
	private function setHeader() {
		header ( "HTTP/1.0 503 Service Unavailable" ); //输出一些跟踪信息
		//header('Last-Modified: '.gmdate('D, d M Y H:i:s', (time() - 60)).' GMT');
		header ( 'X-Powered-By: ' . substr ( $_SERVER ['SERVER_ADDR'], - 3 ) );
		header ( 'X-PVer: Mid Framework' );
	}
	
	/**
	 * Filter request string.
	 *
	 */
	protected function filterRequest() {
		! defined ( 'MAGIC_QUOTES_GPC' ) && define ( 'MAGIC_QUOTES_GPC', get_magic_quotes_gpc () );		
		if (MAGIC_QUOTES_GPC)
			return;
		$this->addSlash ( $_POST );
		$this->addSlash ( $_GET );		
		$this->addSlash ( $_COOKIE );
		$this->addSlash ( $_FILES );
	}
	
	/**
	 * add slashes to string or array
	 *
	 * @param string $string
	 * @param unknown_type $force
	 * @return string addslashed
	 */
	public function addSlash(&$string, $force = 0) {
		if (is_array ( $string )) {
			foreach ( $string as $key => $value ) {
				is_array ( $value ) ? $this->addSlash ( $value ) : $string [$key] = addslashes ( $value );
			}
		} else {
			$string = addslashes ( $value );
		}
	}
	
	/**
	 * throw error message
	 *
	 * @param string $message
	 * @return void
	 */
	private function throwException($message) {
		throw new Exception ( $message );
	}
}
?>